<template>
  <div class="resign-apply-container">
    <el-card class="resign-apply-card">
      <h2 class="form-title">离职申请</h2>
      <el-form
        :model="resignForm"
        :rules="rules"
        ref="formRef"
        label-width="80px"
        class="resign-form"
      >
        <el-form-item label="离职类型" prop="type">
          <el-select v-model="resignForm.type" placeholder="请选择" required>
            <el-option label="主动离职" value="voluntary"></el-option>
            <el-option label="被动离职" value="involuntary"></el-option>
            <el-option label="合同到期" value="contract"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="离职日期" prop="resignDate">
          <el-date-picker
            v-model="resignForm.resignDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            required
          />
        </el-form-item>

        <el-form-item label="离职原因" prop="reason">
          <el-input
            type="textarea"
            v-model="resignForm.reason"
            placeholder="请详细说明离职原因"
            :rows="4"
            required
          />
        </el-form-item>

        <el-form-item label="工作交接人" prop="handoverPerson">
          <el-input
            v-model="resignForm.handoverPerson"
            placeholder="请输入工作交接人"
          />
        </el-form-item>

        <div class="form-actions">
          <el-button
            type="primary"
            @click="submitResign"
            :loading="submitLoading"
          >
            提交申请
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { axios } from "@/stores/index";
import { ElMessage, ElMessageBox } from "element-plus";

import { useAuthStore } from "@/stores/auth";

// 表单状态
const formRef = ref(null);
const submitLoading = ref(false);
const resignForm = ref({
  type: "",
  resignDate: "",
  reason: "",
  handoverPerson: "",
});

// 表单验证规则
const rules = ref({
  type: [{ required: true, message: "请选择离职类型", trigger: "change" }],
  resignDate: [
    { required: true, message: "请选择离职日期", trigger: "change" },
  ],
  reason: [{ required: true, message: "请输入离职原因", trigger: "blur" }],
});

// Axios 实例配置
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器：添加身份验证
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    ElMessage.error("请求发送失败，请检查网络");
    return Promise.reject(error);
  }
);

// 响应拦截器：统一处理响应
request.interceptors.response.use(
  (res) => {
    if (res.data.code !== 200) {
      ElMessage.error(res.data.message || "操作失败");
      return Promise.reject(res.data);
    }
    return res.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      ElMessageBox.confirm("登录已过期，请重新登录", "提示", {
        confirmButtonText: "重新登录",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        localStorage.removeItem("token");
        localStorage.removeItem("isLogin");
        window.location.href = "/login";
      });
    } else {
      ElMessage.error("服务器错误，请稍后重试");
    }
    return Promise.reject(error);
  }
);

// 提交离职申请
const submitResign = async () => {
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) {
    ElMessage.warning("请填写完整并正确的信息！");
    return;
  }

  submitLoading.value = true;
  try {
    // 映射离职类型为数字（假设：voluntary=1, involuntary=2, contract=3）
    const typeMap = {
      voluntary: 1,
      involuntary: 2,
      contract: 3,
    };
    const resignTypeNum = typeMap[resignForm.value.type] || 1;

    
    // 获取当前用户 loginId（来自 Pinia 的 authStore）
    const authStore = useAuthStore();
    const loginId = authStore.currentLoginId; // 假设 loginId 存储在 userInfo.userId 中

    if (!loginId) {
      ElMessage.error("未获取到登录信息，请重新登录");
      return;
    }

    // 第一步：通过 loginId 查询 empId
   const empIdData = await axios.get(`/user/getEmpId`, { params: { loginId } });
   console.log("获取Id接口返回数据：", empIdData); // 查看是否有empId字段
const empId = empIdData; // 直接从 empIdData 中获取 empId
console.log("empId:", empId);
//打印出empId的类型
console.log("empId类型：", typeof empId);
    if (!empId) {
      ElMessage.error("未找到对应员工信息");
      return;
    }

    // 构造符合后端要求的请求体
    const submitData = {
      empId: empId,
      resignType: resignTypeNum,
      expectedLeaveDate: resignForm.value.resignDate ? new Date(resignForm.value.resignDate).toISOString() : "",
      reason: resignForm.value.reason,
      applyStatus: 0, // 默认申请中
      applyTime: new Date().toISOString(), // 当前时间
      handoverPerson: resignForm.value.handoverPerson || "",
    };

    // 调用后端接口
    await request.post("/userResign/insertResignApply", submitData);
    ElMessage.success("离职申请提交成功！等待审批");
    resetForm();
  } catch (error) {
    console.error("离职申请提交失败:", error);
    ElMessage.error(error.response?.data?.message || "提交失败，请检查输入");
  } finally {
    submitLoading.value = false;
  }
};

// 日期格式化
const formatDate = (date) => {
  if (!date) return "";
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
};
</script>

<style scoped>
.resign-apply-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.resign-apply-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
}

.form-title {
  text-align: center;
  color: #303133;
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: 600;
}

.resign-form {
  padding: 0 10px;
}

.el-form-item {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-radius: 4px;
}

:deep(.el-select) {
  width: 100%;
}
</style>
